package main

import (
	"context"
	"fmt"
	"io/ioutil"
	"net/http"
	"sync"
	"time"

	"github.com/prometheus/common/log"
)

type resData struct {
	resp *http.Response
	err  error
}

func doCall(ctx context.Context) {
	transport := http.Transport{
		// 请求频繁可定义全局的client对象并启用长链接
		// 请求不频繁使用短链接
		//    DisableKeepAlives: true,
		DisableKeepAlives: true,
	}
	client := http.Client{
		Transport: &transport,
	}
	respChan := make(chan *resData, 1)

	req, err := http.NewRequest("GET", "http://127.0.0.1:8888", nil)
	if err != nil {
		log.Error("request failed... ")
		return
	}
	// 定义超时管理的ctx
	req = req.WithContext(ctx)
	var wg sync.WaitGroup
	wg.Add(1)
	defer wg.Wait()
	// 开启线程
	go func() {
		// 请求处理
		resp, err := client.Do(req)
		rd := &resData{
			resp: resp,
			err:  err,
		}
		respChan <- rd
		wg.Done()
	}()

	// 处理 请求结果
	select {
	case <-ctx.Done():
		fmt.Println("请求超时....")
	case result := <-respChan:
		if result.err != nil {
			fmt.Println(err)
		}
		fmt.Println("请求成功...")
		defer result.resp.Body.Close()
		// 读取响应结果...
		data, _ := ioutil.ReadAll(result.resp.Body)
		fmt.Println("响应结果:", string(data))
	}
}

// client 客户端  搭配demo3 实现一个超时请求api的解决方案案例
func main() {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
	defer cancel()
	doCall(ctx)
}
